package org.geektimes.configuration.microprofile.config;

import org.eclipse.microprofile.config.Config;
import org.eclipse.microprofile.config.spi.ConfigBuilder;
import org.eclipse.microprofile.config.spi.ConfigProviderResolver;
import org.geektimes.configuration.microprofile.config.converter.StringConverter;
import org.geektimes.configuration.microprofile.config.converter.StringToIntegerConverter;
import org.geektimes.configuration.microprofile.config.converter.StringToLongConverter;
import org.geektimes.configuration.microprofile.config.source.servlet.ServletContextConfigSource;

import javax.servlet.ServletContainerInitializer;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import java.util.Set;

public class DefaultConfigInitializer implements ServletContainerInitializer {

    public final static String microConfig = "microConfig";

    @Override
    public void onStartup(Set<Class<?>> c, ServletContext ctx) throws ServletException {
        final ServletContext servletContext = ctx;
        final ClassLoader classLoader = servletContext.getClassLoader();

        ConfigProviderResolver configProviderResolver = ConfigProviderResolver.instance();
        final ConfigBuilder builder = configProviderResolver.getBuilder();
        builder.forClassLoader(classLoader);
        builder.addDefaultSources();
        builder.addDiscoveredSources();
        builder.withConverters(
                new StringConverter()
                , new StringToIntegerConverter()
                , new StringToLongConverter()
        );
        ServletContextConfigSource servletContextConfigSource = new ServletContextConfigSource(servletContext);
        builder.withSources(servletContextConfigSource);

        final Config config = builder.build();

        configProviderResolver.getConfig(classLoader);

        final String javaVersion = config.getValue("java.version", String.class);
        final String applicationName = config.getValue("application.name", String.class);
        final Integer level = config.getValue("level", Integer.class);
        final String hello = config.getValue("hello", String.class);
        System.out.println("javaVersion:[" + javaVersion + "]");
        System.out.println("applicationName:[" + applicationName + "]");
        System.out.println("level:[" + level + "]");
        System.out.println("hello:[" + hello + "]");
        servletContext.setAttribute(microConfig,config);
    }
}
